package com.funsport.controller.web;

import com.funsport.common.Result;
import com.funsport.entity.Role;
import com.funsport.service.RoleService;
import com.funsport.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 用户角色管理控制器
 */
@RestController
@RequestMapping("/web/user")
public class WebUserRoleController {
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Autowired
    private RoleService roleService;
    
    /**
     * 获取用户的角色列表
     */
    @GetMapping("/{userId}/roles")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<List<Role>> getUserRoles(@PathVariable Long userId) {
        List<Role> roles = roleService.getRolesByUserId(userId);
        return Result.success(roles);
    }
    
    /**
     * 获取用户的角色ID列表
     */
    @GetMapping("/{userId}/role-ids")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<List<Long>> getUserRoleIds(@PathVariable Long userId) {
        List<Long> roleIds = userRoleService.getUserRoleIds(userId);
        return Result.success(roleIds);
    }
    
    /**
     * 分配角色给用户
     */
    @PostMapping("/{userId}/roles")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Void> assignRoles(
            @PathVariable Long userId,
            @RequestBody Map<String, List<Long>> request
    ) {
        List<Long> roleIds = request.get("roleIds");
        userRoleService.assignRoles(userId, roleIds);
        return Result.success();
    }
    
    /**
     * 添加用户角色
     */
    @PostMapping("/{userId}/roles/{roleId}")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Void> addUserRole(
            @PathVariable Long userId,
            @PathVariable Long roleId
    ) {
        userRoleService.addUserRole(userId, roleId);
        return Result.success();
    }
    
    /**
     * 移除用户角色
     */
    @DeleteMapping("/{userId}/roles/{roleId}")
    @PreAuthorize("hasAnyRole('SUPER_ADMIN', 'ADMIN')")
    public Result<Void> removeUserRole(
            @PathVariable Long userId,
            @PathVariable Long roleId
    ) {
        userRoleService.removeUserRole(userId, roleId);
        return Result.success();
    }
}

